import errno
import socket
import threading
from datetime import datetime, timezone, timedelta
from time import time, localtime, strftime

EOL1 = b'\n\n'
EOL2 = b'\n\r\n'

day_of_week = strftime('%a', localtime(time()))
tz = timezone(timedelta(hours=+8))
datetime_with_tz = datetime.now(tz).strftime('%Y-%m-%d %H:%M:%S %Z')

body = '''Hello, World! <h1> From the5fire Django Web Development </h1>'''
response_params = [
    'HTTP/1.0 200 OK',
    f'Date: ${day_of_week} ${datetime_with_tz}',
    'Content-Type: text/html; charset=utf-8',
    'Content-Length:{}\r\n'.format(len(body.encode())),
    body,
]
response = '\r\n'.join(response_params)


def handle_connection(conn, addr):
    request = b""
    while EOL1 not in request and EOL2 not in request:
        request += conn.recv(1024)
    print(request)
    current_thread = threading.currentThread()
    content_length = len(body.format(thread_name=current_thread.name).encode())
    print(current_thread.name)
    conn.send(response.format(thread_name=current_thread.name, length=content_length).encode())
    conn.close()


def main():
    # socket.AF_INET 用于服务器与服务器间网络通信
    # socket.SOCK_STREAM 用于基于TCP的流式socket 通信
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # 设置端口可复用，保证我们每次按Ctrl + C 组合件之后，快速重启
    server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server_socket.bind(('127.0.0.1', 8000))
    server_socket.listen(10)
    print('http:127.0.0.1:8000')
    # server_socket.setblocking(0)  # unblock mode
    try:
        i = 0
        while True:
            try:
                conn, address = server_socket.accept()
            except socket.error as e:
                if e.args[0] != errno.EAGAIN:
                    raise
                continue
            i += 1
            print(i)
            t = threading.Thread(target=handle_connection, args=(conn, address), name='thread-%s' % i)
            t.start()
    finally:
        server_socket.close()


if __name__ == '__main__':
    main()
